#include "QROHost_P.h"

void QROHost::Private::onStart(QString url)
{
    m_host->setHostUrl(url);
    m_host->enableRemoting(m_registerInterface);
}

int QROHost::Private::onRegisterChannel(QVariant cookie){

    if(m_delegate)
    {
        bool ret = m_delegate->onClientTryConnect(cookie);
        if(!ret) return -1;
    }

    auto id = allocChannelID();
    QROClientPrivate init;
    init.id = id;
    init.cookie = cookie;
    auto client = new QROClient(init);
    QObject::connect(client,&QObject::destroyed,[=](){
        onUnregisterChannel(id);
    });

    auto channel = new RemoteInterfaceSourceImp(this);
    channel->setId(id);
    channel->setOwnedObjs({});
    QString shareName = ChannelShareName.arg(id);

    bool r = m_host->enableRemoting(channel,shareName);

    auto data = std::make_shared<RemoteClientChannel>();
    data->channel = channel;
    data->id = id;
    data->client = client;

    m_channels[id] = data;
    if(m_delegate)
    {
        m_delegate->onClientConnected(client);
    }


    return id;
}

void QROHost::Private::onUnregisterChannel(int id){

    auto data = m_channels[id];

    if(!data) return;
    //将该客户端占领的对象收归
    m_host->disableRemoting(data->channel);
    delete data->channel;
    m_channels.erase(id);
}
